package com.cn.server.handler.websocket;

import com.cn.common.core.FastJsonUtils;
import com.cn.common.core.exception.ErrorResponse;
import com.cn.common.core.model.Request;
import com.cn.common.core.model.Result;
import com.cn.common.core.model.ResultCode;
import com.cn.common.core.session.Session;
import com.cn.server.msg.MessageHandler;
import com.cn.common.module.chat.request.PrivateChatRequest;
import com.cn.server.Constant;
import com.cn.server.module.chat.handler.ChatHandler;
import com.cn.server.module.chat.handler.ChatHandlerImpl;
import com.cn.server.module.login.ImUser;

import java.nio.charset.Charset;

public class WebSocketSingleChatHandler implements MessageHandler {


    private ChatHandler chatHandler = new ChatHandlerImpl();

    @Override
    public Result<?> handle(Request packet, Session session) {
        Object attachment = session.getAttachment();
        if (attachment != null) {
            ImUser imUser = (ImUser) attachment;
            String json = new String(packet.getData(), Charset.defaultCharset());
            PrivateChatRequest request = FastJsonUtils.fromJson(json, PrivateChatRequest.class);
            return chatHandler.privateChat(imUser.getLoginName(), request.getBytes());
        } else {
            //会话未登录拒绝请求
            return Result.ERROR(new ErrorResponse(ResultCode.LOGIN_PLEASE, Constant.UN_LOGIN_ERROR));
        }

    }
}
